﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using SkyR1deR;

class Program
{
    private static TCP.Server TCPServer;
    private static Modbus.Slave ModbusSlave;

    static void Main(string[] args)
    {
        TCPServer = new TCP.Server(502);
        TCPServer.clientConnectedEvent += new TCP.Server.clientConnectedEventHandler(clientConnectedEvent);
        TCPServer.clientDisconnectedEvent += new TCP.Server.clientDisconnectedEventHandler(clientDisconnectedEvent);
        TCPServer.clientDataReceivedEvent += new TCP.Server.clientDataEventHandler(clientDataReceived);
        TCPServer.clientDataSendedEvent += new TCP.Server.clientDataEventHandler(clientDataSended);

        ModbusSlave = new Modbus.Slave();
    }

    private static void clientConnectedEvent(TcpClient client)
    {            
        Console.WriteLine(client.Client.RemoteEndPoint.ToString() + " Connected");
    }

    private static void clientDisconnectedEvent(TcpClient client, string raison)
    {
        Console.WriteLine(client.Client.RemoteEndPoint.ToString() + " Disconnected : " + raison);
    }

    private static void clientDataReceived(TcpClient client, byte[] data)
    {
        if (data != null && data.Length > 0 && data[0] != 13) {
            Modbus.Request.reqTCP TCP_ModbusRequest = new Modbus.Request.reqTCP(data);
            Console.WriteLine(DateTime.Now.ToString() + " << " + client.Client.RemoteEndPoint.ToString() + " | " + TCP_ModbusRequest.ToString());
            byte[] ModbusResponse = ModbusSlave.ComputeRequest(TCP_ModbusRequest.PDU);
            byte[] TCP_ModbusResponse = new byte[7 + ModbusResponse.Length];
            Array.ConstrainedCopy(TCP_ModbusRequest.MBAP, 0, TCP_ModbusResponse, 0, 7);
            TCP_ModbusResponse[4] = Tools.getByteHI((UInt16) ModbusResponse.Length);
            TCP_ModbusResponse[5] = Tools.getByteLO((UInt16) ModbusResponse.Length);
            TCPServer.SendTo(client, TCP_ModbusResponse);
        }
    }

    private static void clientDataSended(TcpClient client, byte[] data)
    {
        Console.WriteLine(DateTime.Now.ToString() + " >> " + client.Client.RemoteEndPoint.ToString() + " | " + Tools.bytesToString(data));
    }

}
